import java.util.Random;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * Creat with IntelliJ IDEA
 * Description:
 * User:WZW
 * Date:2022-09-08
 * Time:23:25
 */
public class Demo21 {
    public static void main0(String[] args) throws InterruptedException {
        BlockingDeque<String> queue = new LinkedBlockingDeque<>();
        // 入队
        queue.put("abc");
        // 出队，若没有put直接take，则会阻塞
        String elem = queue.take();
    }

    public static void main(String[] args) {
        BlockingQueue<Integer> blockingQueue = new LinkedBlockingDeque<>();

        Thread customer = new Thread(()-> {
            while (true) {
                try {
                    int value = blockingQueue.take();
                    System.out.println("消费元素：" + value);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"消费者");
        customer.start();

        Thread producer = new Thread(()->{
            Random random = new Random();
            while (true) {
                try {
                    int num = random.nextInt(1000);
                    System.out.println("生产元素：" + num);
                    blockingQueue.put(num);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"生产者");
        producer.start();

        try {
            customer.join();
            producer.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
